//main
import React, { useContext, useState } from "react";
import { connect } from "react-redux";
import { Button, Input, ThemeProvider } from "@material-ui/core";
//data
import Context from "../../Context.js";
//funcs
import { createHash } from "../../func/chatList/chat";
import { newChat } from "../../func/chatList/chat";
//styles
import { useStyles } from "./Navbar.jss";

function AddPlace(props) {
  const { theme, setCurrentChat, WSConnectStatus } = useContext(Context);
  const classes = useStyles(theme);

  const [InputChatIdValue, setInputChatIdValue] = useState("");
  return (
    <ThemeProvider theme={theme}>
      <div className={classes.addPlace}>
        <Input
          className={classes.input}
          value={InputChatIdValue}
          onChange={(e) => setInputChatIdValue(e.target.value)}
          onKeyPress={joinInputEnter}
          placeholder="enter secret key"
        />
        <Button
          className={classes.button}
          variant="contained"
          color="primary"
          onClick={join}
        >
          join
        </Button>
      </div>
    </ThemeProvider>
  );

  //join to chat
  async function join(e) {
    if (InputChatIdValue) {
      try {
        await newChat(InputChatIdValue, WSConnectStatus);
        setCurrentChat(createHash(InputChatIdValue));
      } catch (err) {
        console.error(err);
      }
    }
    setInputChatIdValue("");
  }

  function joinInputEnter(e) {
    e.key === "Enter" && join();
  }
}

const mapStateToProps = (state) => {
  return {
    chats: state.chats,
  };
};

const mapDispathToProps = {
  // addChat,
};

export default connect(mapStateToProps, mapDispathToProps)(AddPlace);
